package com.jxw.cloudpen.web.netty.handler;

import com.jxw.cloudpen.web.netty.Entity.StreamData;
import com.jxw.cloudpen.web.netty.common.ExecutorScheduler;
import com.jxw.cloudpen.web.netty.common.LocalSession;
import com.jxw.cloudpen.web.netty.common.SessionManger;
import com.jxw.cloudpen.web.netty.google.InfiniteStreamRecognize6;
import com.jxw.cloudpen.web.netty.google.StreamRecognManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Slf4j
//@Service("ChatRedirectHandler")
public class BusinHandler extends ChannelInboundHandlerAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(BusinHandler.class);

    /**
     * 收到消息
     */
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
//        log.info( "接受rpc数据"+ msg);
        //判断消息实例
        if (null == msg || !(msg instanceof StreamData)) {
            super.channelRead(ctx, msg);
            return;
        }
        log.info("busin is execute");
        StreamData message = (StreamData) msg;
        //取得请求类型

        if (!message.getType().equals(6)) {
            super.channelRead(ctx, msg);
            return;
        }
        //异步处理转发的逻辑
//        FutureTaskScheduler.add(() ->
//        {
        //判断是否登录
        LocalSession session = SessionManger.get(message.getClientId());
//            if (null != session && session.isLogin()) {
//                return;
//            }
        if (null == session) {
            return;
        }
//            log.info("收到客户端消息："+rpcRequest);
        //执行任务
        ExecutorScheduler.add(new ServiceBusinCallable(message,session));

//        InfiniteStreamRecognize6 infiniteStreamRecognize6 = StreamRecognManager.map.get(message.getClientId());
//
//        if(infiniteStreamRecognize6==null){
//            infiniteStreamRecognize6 = new InfiniteStreamRecognize6();
//            infiniteStreamRecognize6.infiniteStreamingRecognize("en-US");
//            StreamRecognManager.map.put(message.getClientId(),infiniteStreamRecognize6);
//        }
////                InfiniteStreamRecognize6.infiniteStreamingRecognize( "en-US");
//        infiniteStreamRecognize6.sharedQueue.put(message.getData());
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx)
            throws Exception {
        //channel失效，从Map中移除
        Channel channel = ctx.channel();
        ChannelId channelId = channel.id();
        String idStr = channelId.asLongText();
        LOGGER.info("服务端与客户端断开连接:" + idStr);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // ..

        //捕捉异常信息
        cause.printStackTrace();
        ctx.close();


    }
}
